package com.eos.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.hf.utils.PropertiesParser;

/**
 * 
 * 
 * @author administrator
 * @date 2012-05-24
 * @version 1.0
 * 
 */
public class IllegalCharsFilter implements Filter {

	private String[] illegalcharsarray = null;
	private String illegalchars = new PropertiesParser().readProperties("core_key", "illegalchars");

	public void destroy() {
		System.out.println("过滤非法字符过滤器被销毁...");
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) arg0;

		HttpServletRequestWrapper request = new HttpServletRequestWrapper(req);

		arg2.doFilter(request, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		if (null != illegalchars)
			illegalcharsarray = illegalchars.split(",");
		System.out.println("系统过滤非法字符过滤器启动...");
	}

	public class HttpServletRequestWrapper extends
			javax.servlet.http.HttpServletRequestWrapper {

		public HttpServletRequestWrapper(HttpServletRequest request) {
			super(request);
		}

		public String getParameter(String name) {
			String re = null;
			re = encoding(((HttpServletRequest) this.getRequest())
					.getParameter(name));
			return re;
		}

		public String[] getParameterValues(String name) {
			String[] re = ((HttpServletRequest) this.getRequest())
					.getParameterValues(name);
			if (re != null) {
				for (int i = 0; i < re.length; i++) {
					re[i] = encoding(re[i].trim());
				}
			}
			return re;
		}

		/**
		 * 
		 * 
		 * @param name
		 * @return
		 */
		public String encoding(String name) {
			String value = null;
			if (name != null) {
				for (int i = 0; i < illegalcharsarray.length; i++) {
					if (name.contains(illegalcharsarray[i]))
						name = name.replace(illegalcharsarray[i], "");
				}
				value = name;
			}
			return value;
		}
	}

}
